import cgi
import wsgiref.handlers

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext import db	
from utilities  import session

import os
from google.appengine.ext.webapp import template


class Greeting(db.Model):
  author = db.UserProperty()
  content = db.StringProperty(multiline=True)
  date = db.DateTimeProperty(auto_now_add=True)

class MainPage(webapp.RequestHandler):
  def get(self):
    greetings_query = Greeting.all().order('-date')
    greetings = greetings_query.fetch(5)
    
    self.sess = session.Session()
    self.sess.setFlashData('You set flash data! <a href="/session">Refresh this page</a> and this message is gone!')
    if self.request.get('showPost') == "true":
        self.sess['showPost'] = True
    else:
        self.sess['showPost'] = True
        
    if self.request.get('showPost') == "false":
        self.sess.deleteSession()
        
    user = users.get_current_user()

    if user:
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'

    template_values = {
      'greetings': greetings,
      'url': url,
      'url_linktext': url_linktext,
      'user': user,
      'sess': self.sess,
      }

    path = os.path.join(os.path.dirname(__file__), 'flexible_grids.html')
    self.response.out.write(template.render(path, template_values))


class Guestbook(webapp.RequestHandler):
  def post(self):
    greeting = Greeting()

    if users.get_current_user():
      greeting.author = users.get_current_user()

    greeting.content = self.request.get('content')
    greeting.put()
    self.redirect('/')

class ShowUserGadget(webapp.RequestHandler):
    def get(self):
      user = users.get_current_user()
      if users.get_current_user():
        url = users.create_logout_url(self.request.uri)
        url_linktext = 'Logout'
      else:
        url = users.create_login_url(self.request.uri)
        url_linktext = 'Login'
      
      template_values = {
        'user': user,
        'url': url,
        'url_linktext': url_linktext,        
      }
      self.response.headers["Content-Type"] = "text/xml"
      path = os.path.join(os.path.dirname(__file__), 'userGadget.xml')
      self.response.out.write(template.render(path, template_values))


def main():
  application = webapp.WSGIApplication(
                                       [('/', MainPage),
                                        ('/sign', Guestbook),
                                        ('/userGadget', ShowUserGadget)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()
